package com.example.hzcccc.weather;


import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;


public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private DrawerLayout mDrawerLayout;
    private NavigationView mNavigationView;
    private ActionBarDrawerToggle mActionBarDrawerToggle;
    private ViewPager mViewPager;
    private ArrayList<Fragment> mFragmentList;
    Toolbar toolbar;

    SQLdm s;
    SQLiteDatabase db;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.id_drawerlayout);
        mNavigationView = (NavigationView) findViewById(R.id.id_nvmenu);
        Toolbar toolbar = (Toolbar) findViewById(R.id.id_toolbar);
        SQLdm s = new SQLdm();
        SQLiteDatabase db = s.openDatabase(MainActivity.this);
        Cursor cursor  = db.rawQuery("SELECT * FROM managercity",null);
        if(cursor.getCount()!=0) {
            cursor.moveToFirst();
            toolbar.setTitle(cursor.getString(0));
        }


        MainActivity.this.setSupportActionBar(toolbar);
        final ActionBar ab = MainActivity.this.getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setHomeButtonEnabled(true);

        //ab.setDisplayHomeAsUpEnabled(true);


        mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        mActionBarDrawerToggle.syncState();
        mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);


        mNavigationView.setNavigationItemSelectedListener(this);




        updata();
        initViewPager();

    }

    @Override
    protected void onStart() {
        super.onStart();
        updata();
        initViewPager();

    }
    public void updata(){
        new Thread(){
            @Override
            public void run() {
                super.run();
                SQLdm s = new SQLdm();
                SQLiteDatabase db = s.openDatabase(MainActivity.this);
                Cursor cursor  = db.rawQuery("SELECT * FROM managercity",null);
                if(cursor.moveToFirst()){
                    do{
                        String httpUrl = "http://apis.baidu.com/apistore/weatherservice/recentweathers";
                        String httpArg = "cityname=" + cursor.getString(0) + "&cityid=" + cursor.getString(2);
                        String jsonResult = request(httpUrl, httpArg);
                        jsonResult = convert(jsonResult);
                        try {
                            JSONObject jsonObject = new JSONObject(jsonResult);
                            JSONObject retData = jsonObject.getJSONObject("retData");
                            JSONObject today = retData.getJSONObject("today");
                            JSONArray forecast = retData.getJSONArray("forecast");
                            //写入到数据库中
                            db.execSQL("UPDATE managercity SET today = '" + today.getString("week") + "' WHERE NAME = '" + cursor.getString(0) + "'");
                            db.execSQL("UPDATE managercity SET curtemp = '" + today.getString("curTemp") + "' WHERE NAME = '" + cursor.getString(0) + "'");
                            db.execSQL("UPDATE managercity SET today_hightemp = '" + today.getString("hightemp") + "' WHERE NAME = '" + cursor.getString(0) + "'");
                            db.execSQL("UPDATE managercity SET toady_lowtemp = '" + today.getString("lowtemp") + "' WHERE NAME = '" + cursor.getString(0) + "'");
                            db.execSQL("UPDATE managercity SET today_type = '" + today.getString("type") + "' WHERE NAME = '" + cursor.getString(0) + "'");
                            db.execSQL("UPDATE managercity SET tomorrow = '" + forecast.getJSONObject(0).getString("week") + "' WHERE NAME = '" + cursor.getString(0) + "'");
                            db.execSQL("UPDATE managercity SET tomorrow_hightemp = '" + forecast.getJSONObject(0).getString("hightemp") + "' WHERE NAME = '" + cursor.getString(0) + "'");
                            db.execSQL("UPDATE managercity SET tomorrow_lowtemp = '" + forecast.getJSONObject(0).getString("lowtemp") + "' WHERE NAME = '" + cursor.getString(0) + "'");
                            db.execSQL("UPDATE managercity SET tomorrow_type = '" + forecast.getJSONObject(0).getString("type") + "' WHERE NAME = '" + cursor.getString(0) + "'");
                            db.execSQL("UPDATE managercity SET TDAT = '" + forecast.getJSONObject(1).getString("week") + "' WHERE NAME = '" + cursor.getString(0) + "'");
                            db.execSQL("UPDATE managercity SET TDAT_hightemp = '" + forecast.getJSONObject(1).getString("hightemp") + "' WHERE NAME = '" + cursor.getString(0) + "'");
                            db.execSQL("UPDATE managercity SET TDAT_lowtemp = '" + forecast.getJSONObject(1).getString("lowtemp") + "' WHERE NAME = '" + cursor.getString(0) + "'");
                            db.execSQL("UPDATE managercity SET TDAT_type = '" + forecast.getJSONObject(1).getString("type") + "' WHERE NAME = '" + cursor.getString(0) + "'");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }while (cursor.moveToNext());
                }
            }
        }.start();
    }


    //Unicode转换为汉字
    public String convert(String theString) {
        char aChar;
        int len = theString.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len; ) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed   \\uxxxx   encoding.");
                        }

                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }
            } else
                outBuffer.append(aChar);
        }
        return outBuffer.toString();
    }

    private String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("POST");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey", "868780943648512eaaa9f020c8c3fce8");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private void initViewPager() {
        SQLdm s = new SQLdm();
        SQLiteDatabase db = s.openDatabase(MainActivity.this);
        final Cursor cursor  = db.rawQuery("SELECT * FROM managercity",null);
        int number = cursor.getCount();

        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
        mFragmentList = new ArrayList<Fragment>();
        cursor.moveToFirst();

        for (int i =1;i<=number;i++){
            Bundle args = new Bundle();
            String sToady =cursor.getString(4) + cursor.getString(5) + cursor.getString(6) + cursor.getString(7) + cursor.getString(16);
            String sTomorrow = cursor.getString(8) + cursor.getString(9) + cursor.getString(10) + cursor.getString(11);
            String sTDAT = cursor.getString(12) + cursor.getString(13) + cursor.getString(14) + cursor.getString(15);
            args.putString("today",sToady);
            args.putString("tomorrow",sTomorrow);
            args.putString("tdat",sTDAT);
            cursor.moveToNext();
            BaseFragment fragment = new BaseFragment();
            fragment.setArguments(args);
            mFragmentList.add(fragment);
        }

        mViewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), mFragmentList));

        mViewPager.setCurrentItem(0);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                cursor.moveToFirst();
                cursor.moveToPosition(position);
                toolbar = (Toolbar) findViewById(R.id.id_toolbar);
                toolbar.setTitle(cursor.getString(0));


            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mViewPager.setPageTransformer(true, new ZoomOutPageTransformer());
    }


    @Override
    public void onBackPressed() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.id_drawerlayout);
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.menu_navigation_view, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            mDrawerLayout.openDrawer(GravityCompat.START);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
        Intent intent;
        if (id == R.id.nav_add) {
            intent = new Intent(MainActivity.this, ManagerActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_manage) {
            intent = new Intent(MainActivity.this, Main2Activity.class);
            startActivity(intent);
        } else if (id == R.id.nav_setting) {

        } else if (id == R.id.nav_about) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.id_drawerlayout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
